package com.gxs.tga.poc.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gxs.tga.poc.domain.Test;
import com.gxs.tga.poc.domain.TgaDataCard;
import com.gxs.tga.poc.domain.exceptions.DuplicateTgaDataCard;
import com.gxs.tga.poc.domain.exceptions.TgaDataCardNotFound;
import com.gxs.tga.poc.repository.TgaDataCardRepository;

@Service
public class TgaDataCardServiceImpl implements TgaDataCardService
{

	@Resource
	private TgaDataCardRepository tgaDataCardRepository;

	@Override
	@Transactional
	public TgaDataCard create(TgaDataCard card) throws DuplicateTgaDataCard
	{
		
		TgaDataCard existing = this.findById(card.getDatacardRecordId());
		
		if(existing != null)
		{
			throw new DuplicateTgaDataCard();
		}
			
		TgaDataCard createdTgaDataCard = card;
		return tgaDataCardRepository.save(card);
	}

	@Override
	@Transactional
	public TgaDataCard findById(String datacardRecordId)
	{
		return tgaDataCardRepository.findOne(datacardRecordId);
	}

	@Override
	@Transactional(rollbackFor = TgaDataCardNotFound.class)
	public TgaDataCard delete(String datacardRecordId) throws TgaDataCardNotFound
	{
		TgaDataCard deletedTgaDataCard = tgaDataCardRepository.findOne(datacardRecordId);

		if (deletedTgaDataCard == null)
			throw new TgaDataCardNotFound();

		tgaDataCardRepository.delete(deletedTgaDataCard);
		return deletedTgaDataCard;
	}

	@Override
	@Transactional
	public List<TgaDataCard> findAll()
	{
		return this.tgaDataCardRepository.findAll();
	}

	@Override
	@Transactional(rollbackFor=TgaDataCardNotFound.class)
	public TgaDataCard update(TgaDataCard test) throws TgaDataCardNotFound {
		TgaDataCard updatedTgaDataCard = tgaDataCardRepository.findOne(test.getDatacardRecordId());
		
		if (updatedTgaDataCard == null)
			throw new TgaDataCardNotFound();
		
		updatedTgaDataCard.setActive(test.getActive());
		updatedTgaDataCard.setDatacardBlob(test.getDatacardBlob());
		updatedTgaDataCard.setSheetId(test.getSheetId());
		updatedTgaDataCard.setSheetName(test.getSheetName());
		updatedTgaDataCard.setShellId(test.getShellId());
		updatedTgaDataCard.setVersion(test.getVersion());
		
		
		return updatedTgaDataCard;
	}
	
	@Override
	@Transactional(rollbackFor=TgaDataCardNotFound.class)
	public List<TgaDataCard> findBySheetIdAndVersion(String sheetId, String version)
	{
		return this.tgaDataCardRepository.findBySheetIdAndVersion(sheetId, version);
	}
	
	@Override
	@Transactional(rollbackFor=TgaDataCardNotFound.class)
	public List<TgaDataCard> findBySheetId(String sheetId)
	{
		return this.tgaDataCardRepository.findBySheetId(sheetId);
	}
	
	@Override
	@Transactional
	public List<TgaDataCard> findByShellId(String shellId)
	{
		return this.tgaDataCardRepository.findByShellId(shellId);
	}

}
